// ==UserScript==
// @date         2021-5-8
// @name         自动填写GCP-宿舍宽带YOUNG登陆的信息
// @namespace    https://gitgcp.com/TimeChicken/autoYOUNG
// @version      1.0
// @description  主要功能是为了减少同学们在登陆YOUNG时输入信息的痛苦，解决学校YOUNG网络认证水平太低造成的不便
// @author       TimeChicken by 匠心客
// @match        125.88.59.131:10001/gz/*
// @icon         http://219.222.251.56:12100/wp-yby/favicon.ico
// @license      MIT
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    // ==学生信息输入区，填写完毕后请保存==
    var stu_id = "你的学号";      // 学生学号
    var stu_pwd = "你的密码";      // 学生密码
    //var over_notice = 0;             // 填写完毕提示框：1为弹出提示；0为不弹出提示
    // ==/学生信息输入区，填写完毕后请保存==
    var req_count = 0;//请求成功次数
    var isLogin = false;//登陆标志位



    //延时函数
    var sleep = function(time) {
        var startTime = new Date().getTime() + parseInt(time, 10);
        while(new Date().getTime() < startTime) {}
    };

    //https://zhidao.baidu.com/question/589365277.html
    function massage_box(text, timeout)
    {
        var layer=document.createElement("div");
        layer.id="layer";
        var style={
            background:"#ffffff",
            position:"absolute",
            zIndex:10,
            width:"300px",
            height:"100px",
            left:"550px",
            top:"300px",
            align:"center"
        };
        for(var i in style)
            layer.style[i]=style[i];
        layer.innerHTML = text;
        if(document.getElementById("layer")==null)
        {
            document.body.appendChild(layer);
            setTimeout("document.body.removeChild(layer)",timeout)
        }
    }

    //重写alert方法
    var _alert = window.alert;
    window.alert = function(){
        //console.log(arguments);
        //_alert(arguments[0]);
        if(arguments[0].indexOf("验证码错误") != -1)
        {
            massage_box(arguments[0], 5000);
            sleep(1500);
            location.reload();
        }
        else
        {
            _alert(arguments);
        }
    }

    function get_xmlreq() {
        var xmlhttp = null;

        if(window.XMLHttpRequest)
        {//code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else
        {//code for IE6, IE6
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        return xmlhttp;
    }

    function req_code(sendData) {

        var xmlhttp = get_xmlreq();
        var url = "http://219.222.251.56:12100/cgi-bin/getIdentifyCode.py"/* + "?rnd=" + Math.random()*/;

        function updatePage()
        {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                //deal code .....
                clearTimeout(clearTO);//如果准备状态成功，并且HTTP状态码正确则清除setTimeout*/
                req_code += 1;//请求成功次数
                var result = JSON.parse(xmlhttp.responseText)
                switch (result.status) {
                    case 0:
                    {
                        document.querySelector('#code').value = result.msg;
                        isLogin = true;
                        break;
                    }
                    case 1:
                    {
                        massage_box(result.msg, 2000);
                        break;
                    }
                    case 2:
                    {//识别失败后尝试重新刷新页面获取新的验证码
                        massage_box(result.msg, 2000);
                        //document.querySelector('#image_code').onclick();//重新更换验证码
                        setTimeout(function(){
                            location.reload();
                        }, 1000);
                        break;
                    }
                    default:
                    {
                        alert(result.msg);
                        break;
                    }
                }
            }
        }
        xmlhttp.onreadystatechange = updatePage;

        xmlhttp.open("POST", url, false);
        //xmlhttp.setRequestHeader("If-Modified-Since", "0");
        //xmlhttp.setRequestHeader("Access-Control-Allow-Origin: *");
        xmlhttp.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        /*重点，在请求发布后开始设置setTimeout，如果请求状态不成功也就是readyState != 4 那么setTimeout将会在3秒后运行，并弹出信息提示，要是请求成功，将会清除该setTimeout*/
        var clearTO = setTimeout(function () {
            //alert("验证码识别请求超时，请检查网络设置！(稍后将尝试重连······)"/* + "\nxmlhttp.readyState:" + xmlhttp.readyState + "\nxmlhttp.status:" + xmlhttp.status*/);
            massage_box("验证码识别请求超时，请检查网络设置！(稍后将尝试重连······)", 1000);
        }, 5000);//设置5s超时
        xmlhttp.send(sendData);
    }

    //https://ask.csdn.net/questions/194858
    function getBase64Image(image){
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);

        var dataURL = canvas.toDataURL("image/jpeg");
        dataURL = dataURL.replace("data:image/jpeg;base64,", '');
        var index_d = dataURL.indexOf('=');
        while(index_d != -1)//转化=为%3D，否则解析时会出错
        {
            dataURL = dataURL.replace('=', "%3D");
            index_d = dataURL.indexOf('=');
        }
        var index_j = dataURL.indexOf('+');
        while(index_j != -1)//还要转化+为%20，否则解析时会出错
        {
            dataURL = dataURL.replace('+', "%2B");
            index_j = dataURL.indexOf('+');
        }
        var index_c = dataURL.indexOf('/');
        while(index_c != -1)//还要转化/为%2F，否则解析时会出错
        {
            dataURL = dataURL.replace('/', "%2F");
            index_c = dataURL.indexOf('/');
        }
        dataURL = "imageBase64=" + dataURL;
        return dataURL
    }





    if(document.querySelector('#username') == null || document.querySelector('#password') == null)
    {
        alert("脚本运行发生错误，请向作者反馈");
        return;
    }

    document.querySelector('#username').value = stu_id;
    document.querySelector('#password').value = stu_pwd;
    //req_code(document.querySelector('#password').file[0]);

    /*if(over_notice != 0)
    {
        setTimeout(function()
        {
            alert("您的学号和密码已经输入完毕，请填写验证码登录");
        }, 1000);
    }*/


    var codeForBase64 = getBase64Image(document.querySelector('#image_code'));
    req_code(codeForBase64);

    /*while(!isLogin)
    {
        req_count += 1;
        if(req_count > 3)
        {
            alert("多次请求失败，请反馈作者······(非常感谢您的使用！)")
            return;
        }
        codeForBase64 = getBase64Image(document.querySelector('#image_code'));

        req_code(codeForBase64);
    }*/

    if(isLogin)
    {
        setTimeout(function()
                   {
            document.querySelector('.login_left_btn').onclick();
        }, 1000);
    }

    //alert("hello world!!!");
    // TODO 判断是否登陆成功
    var isLoginSuccess_count = 0;
    while(document.querySelector('#success') == null)
    {
        isLoginSuccess_count += 1;
        if(isLoginSuccess_count > 4)
        {
            alert("登陆失败······");
            return;
        }
        sleep(1000);//延时1s后继续监测是否成功
    }
    //window.location.href='https://www.baidu.com';

    //开发接口


})();